import re

from odoo import models, fields, api
from odoo.exceptions import UserError


class SPresetsBomWizard(models.TransientModel):
    _name = 's.presets.bom.wizard'
    _description = '预设BOM向导'

    product_id = fields.Many2one('product.product', string="MPN", domain=[('is_finished', '=', True)])
    bom_line_ids = fields.One2many('s.presets.bom.line.wizard', 'presets_bom_id', string="物料清单明细行")
    sale_id = fields.Many2one('sale.order', string="销售单")
    partner_id = fields.Many2one('res.partner', string="客户代码")
    sale_order_line_ids = fields.Many2many('sale.order.line', string="销售单行",
                                           compute='_onchange_product_id', store=True)
    sale_qty_count = fields.Float('订单数', compute='_onchange_product_id', store=True)
    sheet_multi = fields.Boolean('多拼版')
    sheet_type = fields.Selection([
        ('sheetA', 'sheetA'),
        ('sheetB', 'sheetB')
    ], default='sheetA', string="拼版", required=True)

    pnl_width = fields.Float('PNL 经向')
    pnl_length = fields.Float('PNL 纬向')
    pnl = fields.Float('PNL / SHEET')
    set_pnl = fields.Float('SET/PNL')

    pcs_set = fields.Float('PCS/SET')
    # 铜厚
    thickness = fields.Float('铜厚')
    # 联系人/电话
    contact = fields.Char('联系人/电话')

    remark = fields.Text('Remark')

    sheet_radial = fields.Float('sheet radial')
    sheet_zonal = fields.Float('sheet zonal')

    sb_workflow_template_id = fields.Many2one(
        'sb.workflow.template', string="Approval Workflow Template",
        domain="[('sb_workflow_template_item_ids', '!=', False), ('workflow_type', '=', 'presets')]")

    parent_id = fields.Many2one('sb.presets.bom', string="Parent")

    # 层数
    layer = fields.Integer('Layer', default=1)
    # 附件
    attachment_ids = fields.One2many('ir.attachment', 'res_id',
                                     domain=[('res_model', '=', 's.presets.bom.wizard')],
                                     string='Attachments')

    @api.constrains('product_id')
    @api.onchange('product_id')
    def _onchange_product_id(self):
        for record in self:
            sale_id = self.env['sale.order'].sudo().search([
                ('product_id', '=', record.product_id.product_tmpl_id.id),
                ('state', '!=', 'cancel')
            ], limit=1)
            if not sale_id:
                sale_id = self.env['sale.order'].sudo().search([
                    ('product_id', '=', record.parent_id.product_id.product_tmpl_id.id),
                    ('state', '!=', 'cancel')
                ], limit=1)
            record.sale_id = sale_id
            record.partner_id = sale_id.partner_id
            record.sale_order_line_ids = sale_id.order_line.filtered(lambda x: x.product_id.detailed_type == 'product')
            record.sale_qty_count = sum(record.sale_order_line_ids.mapped('product_uom_qty'))

    @api.onchange('pnl_width', 'pnl_length', 'thickness')
    @api.depends('bom_line_ids.product_id')
    def _compute_pnl_qty(self):
        self.ensure_one()
        for record in self.bom_line_ids:
            # 仅限产品类别为 塞孔阻焊[IKPS] 阻焊[IKSM]
            categ_id = record.product_id.categ_id
            if not categ_id:
                continue
            if categ_id.code == 'IKPS':
                qty = 0.014 * ((self.pnl_width * self.pnl_length) / 1000000)
                record.product_qty = qty
            elif categ_id.code == 'IKSM':
                if (self.thickness / 35) <= 2:
                    qty = 0.018 * ((self.pnl_width * self.pnl_length) / 1000000)
                    record.product_qty = qty
                elif 2 < (self.thickness / 35) <= 3:
                    qty = 0.025 * ((self.pnl_width * self.pnl_length) / 1000000)
                    record.product_qty = qty
                elif 3 < (self.thickness / 35) <= 4:
                    qty = 0.036 * ((self.pnl_width * self.pnl_length) / 1000000)
                    record.product_qty = qty
                elif (self.thickness / 35) > 4:
                    qty = 0.054 * ((self.pnl_width * self.pnl_length) / 1000000)
                    record.product_qty = qty
            else:
                record.product_qty = 0

    @api.onchange('sheet_multi')
    def _onchange_sheet_multi(self):
        if not self.sheet_multi:
            self.sheet_type = 'sheetA'

    def confirm_save(self):
        """
        生成预设BOM
        """
        if not self.product_id:
            raise UserError('请选择MPN')
        line = []
        for rec in self.bom_line_ids:
            line.append((0, 0, {
                'product_id': rec.product_id.id,
                'product_qty': rec.product_qty,
                'product_length': rec.product_length,
                'product_uom_id': rec.product_uom_id.id,
            }))
        data = {
            'product_id': self.product_id.id,
            'sb_workflow_template_id': self.sb_workflow_template_id.id,
            'sheet_type': self.sheet_type,
            'sheet_multi': self.sheet_multi,
            'pnl_width': self.pnl_width,
            'pnl_length': self.pnl_length,
            'pnl': self.pnl,
            'set_pnl': self.set_pnl,
            'pcs_set': self.pcs_set,
            'thickness': self.thickness,
            'sheet_radial': self.sheet_radial,
            'sheet_zonal': self.sheet_zonal,
            'layer': self.layer,
            'contact': self.contact,
            'remark': self.remark,
            'parent_id': self.parent_id.id,
            'bom_line_ids': line,
        }
        res = self.env['sb.presets.bom'].search([('product_id', '=', self.product_id.id)], limit=1)
        if not res:
            res = self.env['sb.presets.bom'].create(data)
        else:
            res.bom_line_ids.unlink()
            res.write(data)
        attrlist = []
        for i in self.attachment_ids:
            attr = i.copy()
            attr.update({'res_id': res.id, 'res_model': 'sb.presets.bom'})
            attrlist.append(attr.id)
        res.write({'attachment_ids': [(6, 0, attrlist)]})
        if self.sheet_multi and self.sheet_type == 'sheetA':
            # 创建sheetB, 然后跳转到sheetB向导
            product_name = self.product_id.name + '-1'
            f = self.env['product.product'].search([('name', '=', product_name)], limit=1)
            if f:
                res_search = self.env['sb.presets.bom'].search([('product_id', '=', f.id)], limit=1)
                if res_search:
                    return {
                        'type': 'ir.actions.act_window',
                        'res_model': 'sb.presets.bom',
                        'res_id': res_search.id,
                        'view_type': 'form',
                        'view_mode': 'form',
                        'target': 'new',
                    }
                else:
                    line = []
                    for r in self.bom_line_ids:
                        line.append((0, 0, {
                            'product_id': r.product_id.id,
                            'product_qty': r.product_qty,
                            'product_uom_id': r.product_uom_id.id,
                        }))
                    cus_res = self.copy({
                        'product_id': f.id,
                        'sheet_type': 'sheetB',
                        'pnl_width': 0,
                        'pnl_length': 0,
                        'pnl': 0,
                        'set_pnl': 0,
                        'bom_line_ids': line,
                        'parent_id': res.id
                    })
                    return {
                        'type': 'ir.actions.act_window',
                        'res_model': 's.presets.bom.wizard',
                        'res_id': cus_res.id,
                        'view_mode': 'form',
                        'target': 'new',
                    }
            else:
                cus_product = self.product_id.copy(
                    {'name': product_name, 'default_code': product_name, 'presets_bom_id': False})
                line = []
                for r in self.bom_line_ids:
                    line.append((0, 0, {
                        'product_id': r.product_id.id,
                        'product_qty': r.product_qty,
                        'product_uom_id': r.product_uom_id.id,
                    }))
                cus_res = self.copy({
                    'product_id': cus_product.id,
                    'sheet_type': 'sheetB',
                    'pnl_width': 0,
                    'pnl_length': 0,
                    'pnl': 0,
                    'set_pnl': 0,
                    'bom_line_ids': line,
                    'parent_id': res.id
                })
                return {
                    'type': 'ir.actions.act_window',
                    'res_model': 's.presets.bom.wizard',
                    'res_id': cus_res.id,
                    'view_mode': 'form',
                    'target': 'new',
                }

        else:
            # 跳转到预设BOM表单
            return {
                'type': 'ir.actions.act_window',
                'res_model': 'sb.presets.bom',
                'res_id': res.id,
                'view_type': 'form',
                'view_mode': 'form',
                'target': 'current',
            }


class SPresetsBomLineWizard(models.TransientModel):
    _name = 's.presets.bom.line.wizard'
    _description = '预设BOM行向导'

    presets_bom_id = fields.Many2one('s.presets.bom.wizard', string="预设BOM", ondelete='cascade')
    product_id = fields.Many2one('product.product', string="产品")
    categ_id = fields.Many2one('product.category', string="产品类别", related="product_id.categ_id", store=True)
    default_code = fields.Char(string="Default code", related="product_id.default_code", store=True)
    product_length = fields.Float('product length(M)')
    product_qty = fields.Integer(string="PANEL 用量(张)")  # 每叠构中需求的数量
    product_uom_id = fields.Many2one('uom.uom', string="Product Uom")

    @api.onchange('product_id')
    def _onchange_product_id(self):
        for record in self:
            if record.product_id.categ_id.code in ['FOBR', 'FOCF']:
                u = self.env['uom.uom'].search([('code', '=', 'zhang')], limit=1) or record.product_id.uom_id
                record.product_uom_id = u
            else:
                record.product_uom_id = record.product_id.uom_id

    @api.onchange('product_id')
    def _onchange_product_id_pnl_qty(self):
        if self.product_id:
            # 获取铜箔的厚度
            if self.product_id.categ_id.parent_id.code and self.product_id.categ_id.parent_id.code == 'FO':
                match = re.search(r'_([0-9]+)um', self.product_id.name)
                if match:
                    self.product_length = match.group(1)

            # 获取PP的长度
            if self.product_id.categ_id.parent_id.code and self.product_id.categ_id.parent_id.code == 'BS':
                match = re.search(r'X([0-9]+)m', self.product_id.name)
                if match:
                    self.product_length = match.group(1)

            self.presets_bom_id._compute_pnl_qty()
